package com.loren.designer.config;

import com.loren.designer.data.resp.MPage;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

@Configuration
public class JsonConfig {

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        return new Jackson2ObjectMapperBuilder()
                .failOnUnknownProperties(false)
                .serializationInclusion(JsonInclude.Include.ALWAYS)
                .serializerByType(MPage.class, new JsonPageSerializer());
    }

    public static class JsonPageSerializer extends JsonSerializer<MPage<?>> {
        @Override
        public void serialize(MPage<?> page, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            ObjectMapper objectMapper = new ObjectMapper().disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
            jsonGenerator.writeStartObject();
            jsonGenerator.writeFieldName("page");
            jsonGenerator.writeNumber(page.getPage());
            jsonGenerator.writeFieldName("size");
            jsonGenerator.writeNumber(page.getSize());
            jsonGenerator.writeFieldName("total");
            jsonGenerator.writeNumber(page.getTotal());
            jsonGenerator.writeFieldName("pages");
            jsonGenerator.writeNumber(page.getPages());
            jsonGenerator.writeFieldName("list");
            jsonGenerator.writeRawValue(objectMapper.writerWithView(serializerProvider.getActiveView()).writeValueAsString(page.getList()));
            jsonGenerator.writeEndObject();
        }
    }
}